package n876;

/**
 * @author 苏文广
 * @since 2021/9/28
 */
public class Solution {
    public static void main(String[] args) {

    }

    public static ListNode middleNode(ListNode head) {
        ListNode result = head;

        if (head == null || head.next == null) {
            return result;
        }

        // 快慢指针
        // 快指针移动两格, 慢指针移动一格,
        // 当快指针移动到链表尾, 慢指针恰好是中间节点, 如果是奇数 则是中间节点, 如果是偶数, 则是中间第二个节点
        ListNode fast = head;
        ListNode slow = head;
        // 链表尾条件: 当前节点的next是null, 或者 当前节点是null
        while (fast != null && fast.next != null){
            fast = fast.next.next;
            slow=slow.next;
        }

        result = slow;
        return result;
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
